<template>
  <div class="tracetask-container">
    <v-layout wrap justify-center align-center>
      <v-flex md12 d-flex>
        <v-flex md2 px-2>
          <v-text-field v-model="queryForm.taskNumber" :label="$t('task.taskId')"></v-text-field>
        </v-flex>
        <v-flex md2 px-2>
          <v-select :items="sites" :label="$t('task.site')" v-model="queryForm.siteId"></v-select>
        </v-flex>
        <v-flex md2 px-2>
          <v-select
            v-model="queryForm.publishStatus"
            :items="states"
            :label="$t('task.taskStatus')"
          ></v-select>
        </v-flex>

        <v-flex md2 px-2>
          <v-btn round class="subTitle" color="primary" @click="onQuery">
            <span>{{ $t('task.query')}}</span>
            <v-icon>search</v-icon>
          </v-btn>
        </v-flex>

        <v-flex md2 px-2>
          <v-btn round class="subTitle" color="secondary" @click="onPay">
            <span>{{ $t('base.topup')}}</span>
            <v-icon>credit_card</v-icon>
          </v-btn>
        </v-flex>
      </v-flex>

      <!-- table -->
      <v-flex md12 class="elevation-1">
        <v-data-table :headers="headers" :loading="loading" :items="tableData" hide-actions>
          <template v-slot:items="props">
            <td class="text-xs-center">{{ props.item.taskNumber }}</td>
            <td class="text-xs-center">{{ props.item.siteId | Site }}</td>
            <td class="text-xs-center">{{ props.item.productAsin }}</td>
            <td class="text-xs-center">{{ props.item.price }}</td>
            <td class="text-xs-center">{{ props.item.amount }}</td>
            <td class="text-xs-center">{{ props.item.price * props.item.amount }}</td>
            <td class="text-xs-center">{{ props.item.taskType | ServiceFeeFilter }}</td>
            <td class="text-xs-center">{{ getTotalFee(props.item) }}</td>
            <td class="text-xs-center">{{ getTime(props.item.createTime) }}</td>
            <td class="text-xs-center">{{ props.item.publishStatus | TaskStatus }}</td>
            <td class="text-xs-center">
              <v-btn
                round
                flat
                class="subTitle"
                color="accent"
                v-if="props.item.publishStatus === 0"
                @click="onModify(props.item)"
              >
                <div class="mr-1">{{ $t('task.modify')}}</div>
                <v-icon size="20">edit</v-icon>
              </v-btn>
              <v-btn
                v-if="props.item.publishStatus === 0"
                round
                flat
                class="subTitle"
                color="primary"
                @click="onRelease(props.item)"
              >
                <div class="mr-1">{{ $t('task.release')}}</div>
                <v-icon size="20">send</v-icon>
              </v-btn>
              <!-- <v-btn
                round
                small
                flat
                class="subTitle"
                color="orange darken-2"
                @click.stop="onPay(props.item)"
              >
                <v-icon size="20">credit_card</v-icon>
                <div class="mr-1">{{ $t('base.pay')}}</div>
              </v-btn>-->
              <!-- <v-btn
                round
                small
                flat
                class="subTitle"
                color="orange darken-2"
                @click.stop="onPay(props.item)"
              >
                <v-icon size="20">credit_card</v-icon>
                <div class="mr-1">{{ $t('base.pay')}}</div>
              </v-btn>-->
              <v-btn
                round
                small
                outline
                class="subTitle"
                color="red lighten-2"
                @click="onStop(props.item)"
                v-if="props.item.publishStatus === 1"
              >
                <div class="mr-1">取消任务</div>
              </v-btn>
              <v-btn
                round
                small
                outline
                class="subTitle"
                color="indigo lighten-2"
                @click="onRepublish(props.item)"
              >
                <div class="mr-1">再来一单</div>
              </v-btn>
            </td>
          </template>
          <template v-slot:no-data>
            <v-alert :value="true" outline color="warning" icon="info">{{ $t('base.nodata') }}</v-alert>
          </template>
        </v-data-table>

        <v-layout class="pagination-wrapper">
          <v-flex md10 d-flex justify-start align-center>
            <v-flex d-flex md2 justify-start align-center>
              <v-flex md4 class="title-color">{{ $t('base.display') }}</v-flex>
              <v-flex md4>
                <v-select
                  @change="onPageOptionChange"
                  :items="pageOptions"
                  v-model="pagination.limit"
                ></v-select>
              </v-flex>
              <v-flex md4 class="title-color">{{ $t('base.limit') }}</v-flex>
            </v-flex>
            <v-flex
              md2
              class="title-color"
            >{{ $t('base.allTog') }} {{ pagination.pageCount }} {{ $t('base.itemData') }}</v-flex>
            <v-flex md2></v-flex>
            <v-flex md4>
              <v-pagination
                @input="onPageChange"
                :length="pagination.pageCount"
                circle
                total-visible="5"
                v-model="pagination.page"
              ></v-pagination>
            </v-flex>
            <v-flex md2></v-flex>
          </v-flex>
        </v-layout>
      </v-flex>
    </v-layout>

    <v-dialog v-model="dialog" max-width="900px">
      <v-card>
        <v-card-title>
          <span class="headline">{{ $t('task.modify') + $t('task.task')}}</span>
        </v-card-title>
        <v-card-text>
          <v-container grid-list-md>
            <v-layout wrap>
              <!-- 选择评测平台 -->
              <v-flex md4>
                <v-select
                  :items="platforms"
                  v-model="dialogItem.platform"
                  :label="$t('task.select') + $t('task.review') + $t('task.platform')"
                ></v-select>
              </v-flex>
              <!-- 选择评测站点 -->

              <v-flex md4>
                <v-select
                  :items="sites"
                  v-model="dialogItem.siteId"
                  :label="$t('task.select') + $t('task.review') + $t('task.site')"
                ></v-select>
              </v-flex>
              <!-- 店铺名称 -->
              <v-flex md4>
                <v-text-field
                  v-model="dialogItem.shopName"
                  :label="$t('task.shop') + $t('task.name') + '*'"
                ></v-text-field>
              </v-flex>
              <!-- 选择产品类别 -->
              <v-flex md4>
                <v-select
                  :items="categories"
                  v-model="dialogItem.category"
                  :label="$t('task.select') + $t('task.product') + $t('task.category')"
                ></v-select>
              </v-flex>
              <!-- 产品标题 (英文) -->
              <v-flex md4>
                <v-text-field
                  :label="$t('task.product') + $t('task.title') + $t('task.English')"
                  v-model="dialogItem.titleEnglish"
                ></v-text-field>
              </v-flex>
              <!-- 产品标题 (中文) -->

              <v-flex md4>
                <v-text-field
                  :label="$t('task.product') + $t('task.title') + $t('task.Chinese')"
                  v-model="dialogItem.titleChinese"
                  counter="20"
                ></v-text-field>
              </v-flex>

              <v-flex md4>
                <v-text-field label="ASIN" v-model="dialogItem.productAsin"></v-text-field>
              </v-flex>
              <v-flex md4>
                <v-text-field
                  :label="$t('task.product') + $t('task.price')"
                  v-model="dialogItem.price"
                ></v-text-field>
              </v-flex>

              <v-flex md4>
                <v-text-field
                  :label="$t('task.product') + $t('task.link')"
                  v-model="dialogItem.interlinkage"
                ></v-text-field>
              </v-flex>

              <v-flex md4>
                <v-text-field
                  :label="$t('task.product') + $t('task.keyword')"
                  v-model="dialogItem.keyword"
                ></v-text-field>
              </v-flex>

              <v-flex md4>
                <v-text-field
                  :label="$t('task.product') + $t('task.position')"
                  v-model="dialogItem.position"
                ></v-text-field>
              </v-flex>

              <v-flex md4>
                <v-text-field
                  :label="$t('task.extraFee')"
                  v-model="dialogItem.addedFee"
                  append-icon="attach_money"
                ></v-text-field>
              </v-flex>

              <v-flex md8>
                <v-text-field
                  :label="$t('task.review') + $t('task.count')"
                  :hint="$t('task.reviewTip')"
                  v-model="dialogItem.amount"
                ></v-text-field>
              </v-flex>

              <v-flex md12>
                <v-radio-group
                  :label="$t('task.product') + $t('task.type')"
                  v-model="dialogItem.taskType"
                >
                  <v-radio
                    v-for="(item, i) in taskTypes"
                    :key="i"
                    :label="item.text"
                    :value="item.value"
                    color="primary"
                  ></v-radio>
                </v-radio-group>
              </v-flex>

              <v-flex
                md12
                class="text-xs-left title-color"
              >{{ $t('task.product') + $t('task.mainImage') }}</v-flex>
              <v-flex
                md8
                class="droppable elevation-4"
                id="dropPanel"
                @drop="onDrop"
                @dragover="onDragOver"
              >
                <div class="fill-height fill-width">
                  <img
                    class="preview-image"
                    :src="dialogItem.productImg"
                    alt
                    v-if="dialogItem.productImg !== ''"
                  />
                </div>

                <v-icon
                  v-if="dialogItem.productImg === ''"
                  class="cloud-icon"
                  size="32"
                >cloud_upload</v-icon>
                <span
                  v-if="dialogItem.productImg === ''"
                  class="upload-tip title-color"
                >{{ $t('task.selectFile') }}</span>

                <input
                  type="file"
                  accept="image/*"
                  name="imageInput"
                  class="file-input"
                  @change="onFileInputChange"
                />
              </v-flex>

              <!-- <v-flex md8>
                <div class="subTitle text-xs-left">{{ totalPrice }}</div>
              </v-flex>-->
            </v-layout>
          </v-container>
          <small>{{ $t('base.requiredField') }}</small>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="blue darken-1" flat @click="onDialogConfirm">{{ $t('base.confirm') }}</v-btn>
          <v-btn color="grey darken-1" flat @click="dialog = false">{{ $t('base.cancel') }}</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <v-dialog v-model="modal" persistent max-width="290">
      <v-card>
        <v-card-title class="title">{{ modalTitle }}</v-card-title>
        <v-card-text class="title">{{ modalContent }}</v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="blue darken-1" flat @click="onModalConfirm">确定</v-btn>
          <v-btn color="grey darken-1" flat @click="modal = false">取消</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>


<script lang="ts">
// 使用类装饰器
import { Component, Vue } from "vue-property-decorator";
import { ReqTaskInfo, TaskInfo, RespFileVo } from "@/api/bean";
import { Task, Order, FileHandler } from "@/api";
import { KV, Pagination } from "@/utils/type";
import {
  PageOptions,
  CategoryKV,
  Rate,
  ServiceFee,
  SiteKV
} from "@/utils/constants";
import { forEach } from "lodash";
import { getTime } from "@/utils/commonUtils";
import Cookie from 'js-cookie';
declare const $Vue: Vue;

@Component
export default class TraceTask extends Vue {
  private platforms: Array<KV> = [
    {
      text: "Amazon",
      value: 1
    }
  ];

  private sites: Array<KV> = SiteKV;

  private categories: Array<KV> = CategoryKV.slice();

  private taskTypes: Array<KV> = [];

  private pageOptions: any = [];

  private states: any = [
    {
      text: "全部",
      value: '',
    },
    {
      text: "已发布",
      value: 1,
    },
    {
      text: "未发布",
      value: 0,
    },
    {
      text: "已取消",
      value: -1,
    },
  ];

  private queryForm: any = {
    taskNumber: "",
    siteId: "",
    publishStatus: ""
  };

  private totalPrice: number = 3128;
  private headers: Array<any> = [];

  private tableData: any = [
    // {
    //   siteId: 1,
    //   taskType: 1,
    //   addedFee: 90,
    //   amount: 13,
    //   price: 23,
    //   productAsin: "38djJD732LD"
    // }
  ];

  private imagePreview: string = "";
  private isQuery: boolean = false;
  private loading: boolean = false;

  private dialog: boolean = false;
  private dialogTitle: string = "";
  private dialogType: number = 1;
  private dialogItem: any = {};

  private modal: boolean = false;
  private modalType: number = 1;
  private modalTitle: string = "注意!";
  private modalContent: string = "确认取消订单吗?";
  private modalItem: any = {};

  private imageFile: any = null;

  private pagination: Pagination = {
    pageCount: 20,
    page: 1,
    limit: 10,
    offset: 0
  };

  private requiredFields = [
    "platform",
    "siteId",
    "shopName",
    "category",
    "titleEnglish",
    "productAsin",
    "price",
    "interlinkage",
    "productImg",
    "keyword",
    "position",
    "review",
    "taskType"
  ];

  protected mounted() {
    this.getTaskList();
    $Vue.$emit("title", { message: this.$t("base.traceTask").toString() });
    this.pageOptions = PageOptions.slice();
    this.taskTypes = [
      {
        text: this.$t("task.type1").toString(),
        value: 1
      },
      {
        text: this.$t("task.type2").toString(),
        value: 2
      },
      {
        text: this.$t("task.type3").toString(),
        value: 3
      },
      {
        text: this.$t("task.type4").toString(),
        value: 4
      }
    ];
    this.headers = [
      {
        text: this.$t("task.taskId").toString(),
        align: "center",
        sortable: false,
        value: "name"
      },
      {
        text: this.$t("task.site").toString(),
        align: "center",
        sortable: false,
        value: "calories"
      },
      { text: "ASIN", align: "center", sortable: false, value: "fat" },
      {
        text:
          this.$t("task.product").toString() + this.$t("task.price").toString(),
        align: "center",
        sortable: false,
        value: "carbs"
      },
      {
        text: this.$t("task.taskCount"),
        align: "center",
        sortable: false,
        value: "protein"
      },
      {
        text:
          this.$t("task.product") +
          this.$t("task.totalPrice").toString() +
          "($)",
        align: "center",
        sortable: false,
        value: "iron"
      },
      {
        text: this.$t("task.service") + this.$t("task.fee").toString() + "(￥)",
        align: "center",
        sortable: false,
        value: "iron"
      },
      {
        text: this.$t("task.totalFee") + "(￥)",
        align: "center",
        sortable: false,
        value: "iron"
      },
      {
        text: this.$t("task.createTime"),
        align: "center",
        sortable: false,
        value: "createTime"
      },
      {
        text: this.$t("task.status"),
        align: "center",
        sortable: false,
        value: "status"
      },
      {
        text: this.$t("task.action"),
        align: "center",
        sortable: false,
        value: "action"
      }
    ];
  }

  private onQuery(from?: string) {
    let params: any = {};

    let valid = 0;

    forEach(this.queryForm, (item, key) => {
      // item ? (
      params[key] = item
      // ) : valid++;
    });

    if (valid === 3) {
      // return $Vue.$emit("snackbar", {
      //   message: "请至少填写一个查询条件"
      // });
    }

    if (from === undefined) {
      this.pagination.offset = 0;
      this.pagination.page = 1;
    }
    params.limit = this.pagination.limit;
    params.offset = this.pagination.offset;
    this.isQuery = true;
    this.getTaskList(params);
  }

  private getTime(date: string) {
    return getTime(date);
  }

  /**
   * 计算总费用
   */
  private getTotalFee(item: any): number {
    let totalPrice = item.price * Number(item.amount) * Rate;
    let serviceFee = (Number(ServiceFee[item.taskType]) + Number(item.addedFee)) * Number(item.amount);
    return Number(totalPrice) + Number(serviceFee);
  }

  private onModify(item: any) {
    this.dialogItem = item;
    this.dialog = true;
    this.dialogType = 1;
    this.dialogTitle = '修改任务';
  }

  private onRelease(item: any) {
    this.dialogItem = item;
    // 重新发布任务
    this.republish();
  }

  // 停止活动
  private onStop(item: any) {
    this.modalType = 1;
    this.modal = true;
    this.modalItem = item;
    this.modalContent = "确认停止该活动吗?";
  }


  // 再发布一条
  private onRepublish(item: any) {
    this.releaseTask(item);
  }


  // private onPay(item: any) {
  // this.dialogItem = item;
  // 重新发布任务
  // this.payOrder();
  // }

  private onPageChange(page: any) {
    this.pagination.offset = (page - 1) * this.pagination.limit;
    if (!this.isQuery) {
      this.getTaskList();
    } else {
      this.onQuery("wyvonj");
    }
  }

  private onPay() {
    this.$router.push({
      name: '充值',
    });
  }

  private onPageOptionChange(value: any) {
    this.pagination.page = 1;
    this.pagination.offset = 0;
  }

  private onDrop(ev: any) {
    ev.preventDefault();
    // 获取到拖拽的文件
    const file = ev.dataTransfer.files[0];
    if (!file.name.match(/\.png|\.jp(e)g/g)) {
      return alert("请拖入图片文件");
    }
    this.handleImageFile(file);
  }

  private onDragOver(ev: DragEvent) {
    // 阻止默认事件
    ev.preventDefault();
    return false;
  }

  private onFileInputChange(ev: any) {
    let file = ev.target.files[0];
    this.handleImageFile(file);
  }

  // 处理svg文件 通过拖拽或者input选中
  private handleImageFile(file: File) {
    const reader = new FileReader();
    // this.task.image = file;
    this.imageFile = file;
    reader.onload = (ev: any) => {
      this.imagePreview = ev.target.result;
    };
    // 以文本形式读取
    reader.readAsDataURL(file);
  }

  /**
 * 图片上传完成
 */
  private handleImageUploaded(data: RespFileVo) {
    let fileUrl = data.fileUrl;
    this.dialogItem.productImg = data.fileUrl;
    this.imageFile = null;
    this.imagePreview = "";
    // 上传图片成功后发布新任务
    this.modifyTask();
  }

  private onDialogConfirm() {
    if (this.dialogType === 1) {
      if (this.imageFile !== null) {
        this.uploadFile()
      } else {
        this.modifyTask();
      }
      // 修改任务
    } else if (this.dialogType === 2) {

    }
  }

  private onModalConfirm() {
    if (this.modalType === 1) {
      this.cancelActivity();
    }
  }


  /**
   * 获取任务列表
   */
  private async getTaskList(queryForm?: any) {
    let params: ReqTaskInfo = {
      offset: this.pagination.offset,
      limit: this.pagination.limit,
      createUserId: Number(Cookie.get("seller_userId")),
    };
    if (queryForm) {
      params = queryForm;
      params.createUserId = Number(Cookie.get("seller_userId"))
    }
    const { data } = await Task.getTaskList.r(params);
    console.log("getTaskList", data);
    if (data.result === 0) {
      let $data = data.data;
      this.tableData = $data.dataList;
      this.pagination.pageCount = $data.totalCount
        ? Math.ceil($data.totalCount / this.pagination.limit)
        : 1;
    } else {
      $Vue.$emit("snackbar", {
        message: data.message
      });
    }
  }

  private async modifyTask() {
    const params: TaskInfo = {
      ...this.dialogItem,
    };
    const { data } = await Task.releaseTask.r(params);
    console.log("modifyTask", data);
    $Vue.$emit("snackbar", {
      message: data.message
    });
    this.getTaskList();
    if (data.result === 0) {
      // 
    } else {
    }
  }

  /**
 * 停止活动
 */
  private async cancelActivity() {
    const params = {
      taskId: this.modalItem.taskId
    };
    const { data } = await Task.cancelPublish.r(params);
    console.log("cancelPublish", data);
    $Vue.$emit("snackbar", {
      message: data.message
    });
    this.modal = false;
    if (data.result === 0) {
    } else {
    }
  }

  /**
   * 重新发布任务
   */
  private async republish() {
    const params: any = {
      taskId: this.dialogItem.taskId
    };
    const { data } = await Task.republish.r(params);
    console.log("republish", data);
    $Vue.$emit("snackbar", {
      message: data.message
    });
    $Vue.$emit("balance");
    this.modal = false;

    if (data.result === 0) {
      this.getTaskList();

    } else {
    }
  }


  /**
   * 支付 按任务支付
   */
  private async payOrder() {
    const params: any = {
      orderId: this.dialogItem.orderId
    };
    const { data } = await Order.payOrder.r(params);
    console.log("republish", data);
    $Vue.$emit("snackbar", {
      message: data.message
    });
    $Vue.$emit("balance");

    if (data.result === 0) {
      //
    } else {
    }
  }

  private async uploadFile() {
    const params: FormData = new FormData();
    params.append("file", this.imageFile);
    const config = {
      headers: {
        "Content-Type": "multipart/form-data"
      }
    };
    const { data } = await FileHandler.uploadFile.r(params, config);
    console.log("uploadFile", data);
    if (data.result === 0) {
      if (data.data.length > 0) {
        this.handleImageUploaded(data.data[0]);
      }
      // 图片上传完成后的处理
    } else {
      $Vue.$emit("snackbar", {
        message: data.message
      });
    }
  }

  private async releaseTask(task: any) {
    delete task.taskId;
    const params: any = {
      platform: task.platform,
      siteId: task.siteId,
      category: task.category,
      titleEnglish: task.titleEnglish,
      titleChinese: task.titleChinese,
      productAsin: task.productAsin,
      price: task.price,
      interlinkage: task.interlinkage,
      keyword: task.keyword,
      position: task.position,
      amount: task.amount,
      taskType: task.taskType,
      shopName: task.shopName,
      productImg: task.productImg,
      addedFee: task.addedFee,
      exchange: task.exchange,
      createUserId: Cookie.get('seller_userId'),
      shopId: task.shopId,
      taskNumber: task.taskNumber,
    };
    console.error(task);

    const { data } = await Task.releaseTask.r(params);
    console.log("releaseTask", data);

    if (data.result === 0) {
      $Vue.$emit("balance");
      // this.releaseTask(data.data.taskId);
      $Vue.$emit("snackbar", {
        message: data.message
      });
      this.getTaskList();
    } else {
      $Vue.$emit("snackbar", {
        message: data.message
      });
      this.$router.push({
        name: "充值"
      });
    }
  }
}
</script>

<style lang="less" scoped>
.tracetask-container {
  width: 100%;
  height: 100%;
}
.pagination-wrapper {
  background: white;
  border-top: 1px solid #d4d4d4;
}
</style>


